﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Billing.Utilities;
using System.Data;
using System.Configuration;

namespace Billing.Windows
{
    /// <summary>
    /// Interaction logic for PayBalance.xaml
    /// </summary>
    public partial class CancelBookedCake : Window
    {
        public bool IsValid { get; set; }
        public string CakeBillNo { get; set; }
        //Color cursorEnterColor = Colors.Violet;
        //Color cursorLeaveColor = Color.FromArgb(Convert.ToByte("FF", 16), Convert.ToByte("65", 16), Convert.ToByte("65", 16), Convert.ToByte("65", 16));

        public CancelBookedCake()
        {
            InitializeComponent();

            try
            {
                cmbShape.ItemsSource = Database.GetCakeShapes();
                cmbShape.DisplayMemberPath = "Shape";

                txtBillNo.Focus();
            }
            catch (Exception) { }
        }

        private void Window_KeyUp(object sender, KeyEventArgs e)
        {
            try
            {
                if (e.Key == Key.Escape)
                {
                    this.Close();
                }
                else if (e.Key == Key.F1 && IsValid)
                {
                    if (MessageBoxResult.OK == MessageBox.Show("Do you want to Cancel Cake?", "Cancel Cake", MessageBoxButton.OKCancel, MessageBoxImage.Question))
                    {
                        int result = Database.CancelCake(CakeBillNo);
                        if (result > 0)
                        {
                            MessageBox.Show("Cake Cancelled Successfully", "Cake Cancelled", MessageBoxButton.OK, MessageBoxImage.Information);
                            this.Close();
                        }
                        else
                        {
                            MessageBox.Show("Some Error Has Occurred", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                        }
                    }
                }
                else if (e.Key == Key.Enter && txtBillNo.Text.Trim() != string.Empty)
                {
                    try
                    {
                        if (txtBillNo.Text.Trim() != string.Empty)
                        {
                            DataTable dt = Database.GetCakeDetails(txtBillNo.Text);

                            if (dt == null || dt.Rows.Count < 1)
                            {
                                IsValid = false;
                                lblMsg.Text = "Not a Valid Cake Bill No. Please Enter Valid Cake Bill No.";
                                brdrCustomer.Background = new SolidColorBrush(Colors.DarkOrange);
                                txtCustomerName.Clear();
                                txtPhoneNo.Clear();
                                //txtDeliveryDateTime.Clear();
                                cmbShape.SelectedIndex = -1;
                                txtDesc.Clear();
                                txtMessage.Clear();
                                txtFlavour.Clear();
                                txtQty.Clear();
                                txtTotalAmtNotExtra.Clear();
                                txtAdvance.Clear();
                                txtBalance.Clear();
                                txtNetAmount.Clear();
                                txtDiscount.Clear();
                                txtBookedDate.Clear();
                                txtDeliveryDate.Clear();
                                txtExtraPercentage.Clear();
                                txtModelDesc.Clear();
                                extraAmount.Content = string.Empty;
                                //dtDeliveryDt.Items.Clear();
                            }
                            else
                            {
                                //Checking whether Chef Copy Printed or Not
                                if (bool.Parse(dt.Rows[0]["IsChefCopyPrinted"].ToString()))
                                {
                                    IsValid = false;
                                    lblMsg.Text = "Chef copy already printed.";
                                    lblMsg.Foreground = new SolidColorBrush(Colors.Red);
                                    return;
                                }

                                DateTime deliveredDate;

                                if (dt.Rows[0]["DeliveredDate"] != null && dt.Rows[0]["DeliveredDate"].ToString() != string.Empty)
                                {
                                    deliveredDate = DateTime.Parse(dt.Rows[0]["DeliveredDate"].ToString());
                                }
                                else
                                {
                                    deliveredDate = DateTime.Parse(dt.Rows[0]["DeliveryDate"].ToString());
                                }

                                int hrs = GetTimeIn24Hrs(dt.Rows[0]["DeliveryTime"].ToString());

                                TimeSpan ts = deliveredDate.AddHours(hrs) - DateTime.Now;

                                if (ConfigurationManager.AppSettings["CancelCakeDeliverHours"].ToString() == "0")
                                {
                                    IsValid = true;
                                    lblMsg.Text = "Press F1 to cancel the Cake";
                                    lblMsg.Foreground = new SolidColorBrush(Colors.Blue);
                                }
                                else
                                {
                                    if (ts.TotalHours > int.Parse(ConfigurationManager.AppSettings["CancelCakeDeliverHours"].ToString()))
                                    {
                                        IsValid = true;
                                        lblMsg.Text = "Press F1 to cancel the Cake";
                                        lblMsg.Foreground = new SolidColorBrush(Colors.Blue);
                                    }
                                    else
                                    {
                                        IsValid = false;
                                        lblMsg.Text = "Cake cannot be Cancelled";
                                        lblMsg.Foreground = new SolidColorBrush(Colors.Red);
                                    }
                                }

                                CakeBillNo = dt.Rows[0]["CakeNo"].ToString();
                                brdrCustomer.Background = new SolidColorBrush(Colors.Gray);
                                txtCustomerName.Text = dt.Rows[0]["CustomerName"].ToString();
                                txtPhoneNo.Text = dt.Rows[0]["PhoneNo"].ToString();
                                txtDeliveryDate.Text = DateTime.Parse(dt.Rows[0]["DeliveryDate"].ToString()).ToString("dd-MMM-yyyy") + "  " + dt.Rows[0]["DeliveryTime"].ToString();
                                cmbShape.SelectedIndex = int.Parse(dt.Rows[0]["ShapeID"].ToString()) - 1;
                                txtModelDesc.Text = dt.Rows[0]["AlbumModelDesc"].ToString();
                                txtDesc.Text = dt.Rows[0]["Desc"].ToString();
                                txtMessage.Text = dt.Rows[0]["Message"].ToString();
                                txtFlavour.Text = dt.Rows[0]["Flavour"].ToString();
                                txtQty.Text = dt.Rows[0]["Qty"].ToString();
                                txtTotalAmtNotExtra.Text = dt.Rows[0]["TotalwithoutExtra"].ToString();
                                txtAdvance.Text = dt.Rows[0]["Advance"].ToString();
                                txtBalance.Text = dt.Rows[0]["Balance"].ToString();
                                txtNetAmount.Text = dt.Rows[0]["NetAmount"].ToString();
                                txtDiscount.Text = dt.Rows[0]["DiscountByCost"].ToString();
                                txtBookedDate.Text = DateTime.Parse(dt.Rows[0]["BookedDate"].ToString()).ToString("dd-MMM-yyyy");
                                txtExtraPercentage.Text = dt.Rows[0]["ExtraPercentage"].ToString();
                                extraAmount.Content = dt.Rows[0]["ExtraValue"].ToString();
                            }
                        }
                    }
                    catch (Exception)
                    { }
                }
            }
            catch (Exception) { }
        }

        private int GetTimeIn24Hrs(string time)
        {
            try
            {
                string[] strArr = time.Split(' ');

                if (strArr.Count() == 2)
                {
                    if (strArr[1] == "AM")
                        return Convert.ToInt32(strArr[0]);
                    else
                        return Convert.ToInt32(strArr[0]) + 12;
                }
            }
            catch (Exception) { }
            return 0;
        }

        private void txtBillNo_KeyUp(object sender, KeyEventArgs e)
        {
            try
            {
                if (e.Key == Key.Right && txtBillNo.IsFocused)
                {
                    //dtDeliveryDt.Focus();
                }
            }
            catch (Exception) { }
        }

        private void dtDeliveryDt_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            //dtDeliveryDay.Content = DateTime.Parse((dtDeliveryDt.SelectedItem as ComboBoxItem).Tag.ToString()).DayOfWeek.ToString();
        }

        private void dtDeliveryDt_KeyUp(object sender, KeyEventArgs e)
        {
            try
            {
                if (e.Key == Key.Left)
                {
                    txtBillNo.Focus();
                }
            }
            catch (Exception) { }
        }
    }
}
